package com.xxxx.yoyo.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxxx.yoyo.bean.Type;
import com.xxxx.yoyo.bean.User;
import com.xxxx.yoyo.service.ITypeService;
import com.xxxx.yoyo.service.IUserService;
import com.xxxx.yoyo.service.impl.TypeServiceImpl;
import com.xxxx.yoyo.service.impl.UserServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/index/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private ITypeService typeService = new TypeServiceImpl();
	private IUserService userService = new UserServiceImpl();
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置导航条上的 [登录] 处于选中状态
		request.setAttribute("flag", 6);
		
		//获取 [宠物分类] 列表
		List<Type> typeList = typeService.getTypeList();
		//把typeList存入request,供/index/login.jsp使用
		request.setAttribute("typeList", typeList);
		
		//请求转发,跳转到登录页面 /index/login.jsp
		request.getRequestDispatcher("/index/login.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码格式为UTF-8 -----解决中文乱码
		request.setCharacterEncoding("UTF-8");
		
		//获取前端传递过来的登录信息(获取传递过来的参数)
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//根据用户名和密码查询用户
		User user = userService.getUserByUsernameAndPassword(username, password);
		if(user == null) {//如果没有查到--->用户名或者密码错误!
			//给出一个错误提示
			request.setAttribute("msg", "登录失败!用户名或者密码错误!");
			
			//设置导航条上的 [登录] 处于选中状态
			request.setAttribute("flag", 6);
			
			//获取 [宠物分类] 列表
			List<Type> typeList = typeService.getTypeList();
			//把typeList存入request,供/index/login.jsp使用
			request.setAttribute("typeList", typeList);
			
			//请求转发,还回到登录页面/index/login.jsp
			request.getRequestDispatcher("/index/login.jsp").forward(request, response);
		}else {//查到了----> 登录成功!
			HttpSession session = request.getSession();
			//登录之后,把用户存入session,这样导航条会根据是否登录显示不同的导航信息
			session.setAttribute("user", user);
			
			//请求转发,跳转到首页是servlet
			request.getRequestDispatcher("/index/index").forward(request, response);
		}
		
	}

}
